package com.diandi.signature.controller.cainfo;


import com.diandi.signature.enums.fdd.ReturnCode;
import com.diandi.signature.enums.platfrom.InterfactType;
import com.diandi.signature.manager.CAInfo.SignatureCAManager;
import com.diandi.signature.properties.SignatureProperties;
import com.diandi.signature.sign.SignUtil;
import com.diandi.signature.sign.Tools;
import com.diandi.signature.signatureca.SignatureCAService;
import com.diandi.signature.url.CreateTradeNo;
import com.diandi.signature.utils.CheckParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 签章个人CA证书申请接口
* @author mwz
* @create 2017-08-22 21:47
* @version V1.0.0
*
*/
@RestController
@RequestMapping("/signatureCA")
public class SignatureCAInfoController {
    private static Logger logger = LoggerFactory.getLogger(SignatureCAInfoController.class);

    @Autowired
    private SignatureProperties signatureProperties;

    @Autowired
    private SignatureCAService signatureCAService;



    @Autowired
    private SignatureCAManager signatureCAManager;
    /**
     * 个人申请CA信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/createPersonCAinfo")
    @ResponseBody
    public String persionCreateCAInfo(HttpServletRequest request, HttpServletResponse response){
        String tradeNo = CreateTradeNo.createTradeNo("CA");

        Long sp1 = System.currentTimeMillis();
        logger.info("--["+tradeNo+"] createCA Start--");

        /**
         * 1.1 接收业务端发送来的消息
         */
        Map<String,String> returnMap =  new HashMap<String,String>();
        Map<String, String> params = Tools.getParameterMap(request, false);
        logger.info("收到业务平台[CA申请认证]请求消息requestMap:"+request.getRequestURL()+params);
        returnMap = CheckParams.checkCAParamsIsExist(params, "userId", "customerName", "passCode", "phone", "idCard", "merchantNo");
        if( returnMap != null && !returnMap.isEmpty() ){
            logger.info("收到业务平台[CA申请认证] 参数不能为空："+returnMap.toString()+"--");
            return Tools.createLinkString(returnMap,true);
        }
        /**
         * 1.2 记录日志到mongoService
         */
        Long sp2 = System.currentTimeMillis();
        logger.info("--["+tradeNo+"] step1 use times:"+(sp2-sp1)+"--");

       // mongoService.insert("/signatureCA/createPersonCAinfo", "", params, tradeNo, Long.parseLong(params.get("userId")), "", "请求报文");
        logger.info("--userId:"+params.get("userId")+" businessId:"+params.get("businessId")+" 收到业务平台[CA申请认证]请求消息requestMap:"+request.getRequestURL()+params);
        try {
            logger.info("--userId:"+params.get("userId")+" businessId:"+params.get("businessId")+"收到业务平台[CA申请认证]请求消息:签章平台开始处理");

            /**
             * 2.1  保存业务平台报文
             */
            params.put("InterfaceType", String.valueOf(InterfactType.CA认证.getValue()));
            params.put("tradeNo",tradeNo);
            params.put("requestMsg",params.toString());
            signatureCAManager.insertRcvPkgMsgData( params );

            Long sp3 = System.currentTimeMillis();
            logger.info("--["+tradeNo+"] step2 use times:"+(sp3-sp2)+"--");

            returnMap = signatureCAService.createCA( request, tradeNo );

            Long sp4 = System.currentTimeMillis();
            logger.info("--["+tradeNo+"] step3 use times:"+(sp4-sp3)+"--");

            logger.info("--userId:"+params.get("userId")+" businessId:"+params.get("businessId")+"收到业务平台[CA申请认证]请求消息:账务平台结束处理:" + returnMap.toString() );
            //生成签名
            Map<String, String> signMap = new HashMap<String, String>();
            signMap.putAll(returnMap);
            String sign = SignUtil.signRSA(signMap, signatureProperties.getPayPrivateSign(params.get("merchantNo")), signatureProperties.getCharset());
            returnMap.put("sign",sign);

            /**
             * 4.1  更新业务平台报文
             */
            signMap.put("InterfaceType", String.valueOf(InterfactType.CA认证.getValue()));
            signatureCAManager.updateRcvPkgMsgData(params,signMap);

            Long sp5 = System.currentTimeMillis();
            logger.info("--["+tradeNo+"] step4 use times:"+(sp5-sp4)+"--");

            //mongoService.insert("/signatureCA/createPersonCAinfo", returnMap.toString(), returnMap, tradeNo, Long.parseLong(params.get("userId")), returnMap.get("msg"), "应答报文");
        } catch (Exception e) {
            logger.error(e.toString());
            e.printStackTrace();
            if (returnMap == null || returnMap.isEmpty()){
                returnMap = Tools.createCAReturnParams(ReturnCode.err,null,null);
            }
        }
        logger.info("--["+tradeNo+"] End createCA , TotalTimes:"+(System.currentTimeMillis()-sp1)+"--");
        return Tools.createLinkString(returnMap,true);
    }

    /**
     * 个人查询CA信息
     * userId
     * passCode
     * phone
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/queryPersonCAInfo")
    @ResponseBody
    public String QueryPersionCAInfo(HttpServletRequest request, HttpServletResponse response){
        /**
         * 1.1 接收业务端发送来的消息
         */
        String tradeNo = CreateTradeNo.createTradeNo("QCA");

        Long sp1 = System.currentTimeMillis();
        logger.info("--["+tradeNo+"] queryCA Start--");

        Map<String,String> returnMap =  new HashMap<String,String>();
        Map<String, String> params = Tools.getParameterMap(request, false);
        logger.info("收到业务平台[CA查询]请求消息requestMap:"+request.getRequestURL()+params);
        returnMap = CheckParams.checkParamsIsExist(params, "userId", "sign", "merchantNo", "passCode", "phone");
        if( returnMap != null && !returnMap.isEmpty() ){
            return Tools.createLinkString(returnMap,true);
        }

        Long sp2 = System.currentTimeMillis();
        logger.info("--["+tradeNo+"] step1 use times:"+(sp2-sp1)+"--");

        logger.info("--userId:"+params.get("userId")+" businessId:"+params.get("businessId")+" 收到业务平台[CA查询]请求消息requestMap:"+request.getRequestURL()+params);
        try {
            logger.info("--userId:"+params.get("userId")+" businessId:"+params.get("businessId")+"收到业务平台[CA查询]请求消息:签章平台开始处理");
            /**
             * 1.2 查询相关数据
             */
            returnMap = signatureCAService.queryCAInfo( request );

            Long sp3 = System.currentTimeMillis();
            logger.info("--["+tradeNo+"] step2 use times:"+(sp3-sp2)+"--");

            logger.info("--userId:"+params.get("userId")+" businessId:"+params.get("businessId")+"收到业务平台[CA查询]请求消息:账务平台结束处理:" + returnMap.toString() );
            //生成签名
            String sign = SignUtil.signRSA(returnMap, signatureProperties.getPayPrivateSign(params.get("merchantNo")), signatureProperties.getCharset());

            returnMap.put("sign",sign);

            Long sp4 = System.currentTimeMillis();
            logger.info("--["+tradeNo+"] step1 use times:"+(sp4-sp3)+"--");

        } catch (Exception e) {
            logger.error(e.toString());
            e.printStackTrace();
            returnMap = Tools.createReturnParams(ReturnCode.err,ReturnCode.err.getMsg(),null);
        }

        logger.info("--["+tradeNo+"] End queryCA , TotalTimes:"+(System.currentTimeMillis()-sp1)+"--");

        return Tools.createLinkString(returnMap,true);
    }


    /**
     * 校验参数
     * @param
     * @param params
     * @return
     */
    public  Map<String,String>  CheckParam(   Map<String, String> params ){
        Map<String,String> returnMap =  new HashMap<String,String>();
        returnMap = CheckParams.checkParamsIsExist(params, "userId");
        if (null != returnMap && !returnMap.isEmpty()) {
            logger.info("收到业务平台[CA查询]请求消息其中userId不能为空");
            returnMap = Tools.createReturnParams(ReturnCode.err_1004,ReturnCode.err_1004.getMsg(),null);
            return returnMap;
        }
//        returnMap = CheckParams.checkParamsIsExist(params, "businessId");
//        if (null != returnMap && !returnMap.isEmpty()) {
//            logger.info("收到业务平台[CA查询]请求消息其中businessId不能为空");
//            returnMap = Tools.createReturnParams(ReturnCode.err_1004,ReturnCode.err_1004.getMsg(),null);
//            return returnMap;
//        }
       return null;
    }


}
